package com.hnkywl.sts.webservice.wly.impl;

import com.hnkywl.sts.dao.base.ClxxDao;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.CgdmxDao;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.dao.htgl.HtmxDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.entity.base.Clxx;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Cgdmx;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Htmx;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.util.CalcUtils;
import com.hnkywl.sts.webservice.wly.IPutStorageFeedback;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Jerry on 13-12-31.
 * 接收入库反馈
 */
@Service
public class PutStorageFeedbackService implements IPutStorageFeedback, ApplicationContextAware {

    // private static Logger logger = Logger.getLogger(PutStorageFeedbackService.class);

    private ApplicationContext applicationContext;

    private BmService bmService;
    private HtmxDao htmxDao;
    private ClxxDao clxxDao;
    private CgdmxDao cgdmxDao;
    private KhDao khDao;
    private CgdDao cgdDao;
    private CghtDao cghtDao;
    private WebserviceLogService webserviceLogService;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        bmService = (BmService) applicationContext.getBean("bmService");
        clxxDao = (ClxxDao) applicationContext.getBean("clxxDao");
        htmxDao = (HtmxDao) applicationContext.getBean("htmxDao");
        cgdmxDao = (CgdmxDao) applicationContext.getBean("cgdmxDao");
        khDao = (KhDao) applicationContext.getBean("khDao");
        cgdDao = (CgdDao) applicationContext.getBean("cgdDao");
        cghtDao = (CghtDao) applicationContext.getBean("cghtDao");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }

    /**
     * 1、根据采购合同号找到采购合同实体
     * 2、根据是否完结标志更改采购合同状态如果已完结讲采购合同zt 改成yly
     * 3、根据传过来的明细创建一张采购单包含其中的明细
     *
     * @param json
     * @return
     */
    @Override
    public synchronized String putStorageFeedback(String json, String serialNumber) {
        String result;
        String exception = null;
        try {
            //1、查出所有已审批的采购合同
            this.checkCghtJson(json, serialNumber);//先校验通过
            this.updateCghtAndCreateCgdAndCreateKh(json, serialNumber);//生成采购单和卡号
            result = "{\"code\":\"0\",\"message\":\"入库反馈成功!\"}";
        } catch (Exception e) {
            exception = e.getMessage();
            result = "{\"code\":\"1\",\"message\":\"" + e.getMessage() + "\"}";
        }
        try {
            JSONArray jsonArray = new JSONArray(json);
            webserviceLogService.saveServerLog(
                    PutStorageFeedbackService.class.getName(),
                    "PutStorageFeedbackService",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    PutStorageFeedbackService.class.getName(),
                    "PutStorageFeedbackService",
                    json,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    //校验json
    public void checkCghtJson(String json, String serialNumber) throws Exception {
        if (serialNumber == null || "".equals(serialNumber)) {
            throw new RuntimeException("serialNumber为空!");
        }
        Boolean flag_serialNumber = cgdDao.checkSerialNumber(serialNumber);
        if (!flag_serialNumber) {
            throw new RuntimeException("serialNumber重复!请勿重复入库!");
        }
        if (json == null || json.isEmpty()) {
            throw new RuntimeException("json为空!");
        }

        JSONArray jsonArray = new JSONArray(json);
        int iSize = jsonArray.length();
        if (iSize == 0) {
            throw new RuntimeException("json数组中为空!");
        }


        for (int i = 0; i < iSize; i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            String sellSubNo = (String) jsonObj.get("sellSubNo");
            if (!"null".equals(sellSubNo) && !sellSubNo.isEmpty()) {

                String carNo = (String) jsonObj.get("carNo");//车号
                if (carNo == null || "".equals(carNo)) {
                    throw new RuntimeException("carNo为空!");
                }
                String bindNo = (String) jsonObj.get("bindNo");//捆绑号
                if (bindNo == null || "".equals(bindNo)) {
                    throw new RuntimeException("bindNo为空!");
                }
                String resource_serial_number_1 = (String) jsonObj.get("resource_serial_number_1");//仓储资源唯一号
                if (resource_serial_number_1 == null || "".equals(resource_serial_number_1)) {
                    throw new RuntimeException("resource_serial_number_1为空!");
                }
                String weight = (String) jsonObj.get("weight");//重量
                if (weight == null || "".equals(weight)) {
                    throw new RuntimeException("weight为空!");
                }
                String fDate = (String) jsonObj.get("FDate");//出厂日期
                if (fDate == null || "".equals(fDate)) {
                    //throw new RuntimeException("FDate为空!");
                } else {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        sdf.parse(fDate);
                    } catch (Exception e) {
                        throw new RuntimeException("FDate时间格式错误!");
                    }
                }
            }
        }
    }

    //修改采购合同和创建采购单同时生成卡号
    public void updateCghtAndCreateCgdAndCreateKh(String json, String serialNumber) throws Exception {
        JSONArray jsonArray = new JSONArray(json);
        int iSize = jsonArray.length();
        Cght cght = null;
        List<Cgdmx> cgdmxList = new ArrayList<Cgdmx>();
        List<Kh> khList = new ArrayList<Kh>();
        for (int i = 0; i < iSize; i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            String sellSubNo = (String) jsonObj.get("sellSubNo");
            if (!"null".equals(sellSubNo) && !sellSubNo.isEmpty()) {
                //仓储系统L5S0026   运营系统  L5X0026
                String R = sellSubNo.substring(2, 3);
                if (StringUtils.isNotBlank(R) && R.equals("S")) {
                    String s_1 = sellSubNo.substring(0, 2);
                    String s_2 = sellSubNo.substring(3, sellSubNo.length());
                    sellSubNo = s_1 + "X" + s_2;
                }

                cght = cghtDao.findCghtByXsxtXsdh(sellSubNo);
                if (null == cght || null == cght.getId()) {
                    throw new RuntimeException("没有查询到对应的采购合同!" + sellSubNo);
                }

                String resource_serial_number_1 = (String) jsonObj.get("resource_serial_number_1");//仓储资源唯一号
                String carNo = (String) jsonObj.get("carNo");//车号
                String bindNo = (String) jsonObj.get("bindNo");//捆绑号
//                String fDate = (String) jsonObj.get("FDate");//出厂日期
                Clxx clxx = clxxDao.findClxxByClh(bindNo);//根捆包号查出材料
                if (null == clxx || null == clxx.getId()) {
                    throw new RuntimeException("捆包号为：" + bindNo + "没有推送到运营系统，请联系销售系统!");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                clxx.setZt("1");
                clxxDao.save(clxx);
                // 判断是否已经保存，防止重复入库，捆包号
                Kh khTemp = this.khDao.findKhByRsn(resource_serial_number_1, bindNo);
                if (null != khTemp) {
                    break;
                }

                String number = jsonObj.get("number") == null ? "0" : (String) jsonObj.get("number");//件数
                Double weight = CalcUtils.round(Double.valueOf((String) jsonObj.get("weight")), 6);//重量
                Htmx htmx = htmxDao.findHtmxByHtAndGg(sellSubNo, cght.getId());
                Gg gg = htmx.getWzgg();
                Cgdmx cgdmx = new Cgdmx();
                cgdmx.setLastUpdated(new Date());
                cgdmx.setBhsj(CalcUtils.round(htmx.getBhsj(), 4));
                cgdmx.setHsj(CalcUtils.round(htmx.getHsj(), 4));
                cgdmx.setSjdj(CalcUtils.round(htmx.getHsj(), 4));
                cgdmx.setCcrq(sdf.format(clxx.getCcrq()));
                cgdmx.setGg(gg);
                cgdmx.setXsxt_xsdh(sellSubNo);
                cgdmx.setXsxt_htbm(cght.getXsxt_htbm());
                cgdmx.setCarNo(carNo);
                cgdmx.setBindNo(bindNo);
                cgdmx.setJzfs(htmx.getJzfs());
                cgdmx.setCd(htmx.getCd());
                cgdmx.setJs(Integer.valueOf(number));
                cgdmx.setSbsl(weight);
                cgdmx.setRksl(weight);
                cgdmx.setRkjs(Integer.valueOf(number));
                cgdmx.setSsjs(Integer.valueOf(number));
                cgdmx.setSssl(weight);
                cgdmx.setCreateUser(cght.getCreateUser());
                cgdmx.setCreateDepartment(cght.getCreateDepartment());
                cgdmx.setCreateOrgan(cght.getCreateOrgan());
                cgdmx.setMxh((long) i);
                cgdmxDao.save(cgdmx);
                cgdmxList.add(cgdmx);


                //生成卡号
                Kh kh = new Kh();
                kh.setLastUpdated(new Date());
                kh.setCd(htmx.getCd());
                kh.setKhbm(bmService.getKckhbm(cght.getCk().getId()));
                kh.setKkdsl(weight);
                kh.setRksl(weight);
                kh.setRkrq(new Date());
                kh.setSl(weight);
                kh.setWsdj(CalcUtils.round(htmx.getHsj(), 4));
                kh.setXsxt_price(CalcUtils.round(htmx.getHsj(), 4));
                kh.setCght(cght);
                kh.setCk(cght.getCk());
                kh.setJtwz(gg);
                kh.setCreateUser(cght.getCreateUser());
                kh.setSfdrjg("0");
                kh.setYbc(0);
                kh.setCreateDepartment(cght.getCreateDepartment());
                kh.setCreateOrgan(cght.getCreateOrgan());
                kh.setJs(Integer.valueOf(number));
                kh.setRkjs(Integer.valueOf(number));
                kh.setSbgs(cght.getSbgs());
                kh.setCggs(cght.getSbgs());
                kh.setGys(cght.getHzf());
                kh.setCgdmx(cgdmx);
                kh.setPxh(i);
                kh.setResource_serial_number_1(resource_serial_number_1.trim());
                kh.setCshjs(Integer.valueOf(number));
                kh.setCshsl(weight);
                kh.setJhjs(Integer.valueOf(number));
                kh.setJhsl(weight);
                kh.setRkdh(cght.getHtbm() + "-" + i);
                kh.setXsxt_xsdh(sellSubNo);
                kh.setXsxt_htbm(cght.getXsxt_htbm());
                kh.setCarNo(carNo);
                kh.setBindNo(bindNo);
                kh.setYbc(0);
                kh.setXsxt_fhrq(clxx.getCcrq());
                kh.setSjly("0");
                khDao.save(kh);
                khList.add(kh);
            }
        }
        if (cgdmxList.size() > 0) {
            //生成采购单
            Cgd cgd = new Cgd();
            cgd.setLastUpdated(new Date());
            cgd.setBz("此采购单是根据" + cght.getHtbm() + "采购合同生成!");
            cgd.setCgsj(new Date());
            cgd.setFhrq(new Date());
            cgd.setJhdhrq(new Date());
            cgd.setSerialNumber(serialNumber.trim());
            cgd.setCreateUser(cght.getCreateUser());
            cgd.setCreateDepartment(cght.getCreateDepartment());
            cgd.setCreateOrgan(cght.getCreateOrgan());
            cgd.setCggs(cght.getSbgs());
            cgd.setCght(cght);
            cgd.setDzck(cght.getCk());
            cgd.setGys(cght.getHzf());
            cgd.setCgdh(this.bmService.getCgdbm("cgrk"));
            cgd.setCglx("cgrk");
            cgd.setZt("ysp");
            cgd.setSl(cght.getSl().toString());
            cgd.setRksj(new Date());
            cgd.setRkr(cght.getSbr());
            cgd.setSbgs(cght.getSbgs());
            cgd.setSbbm(cght.getSbbm());
            cgd.setSbr(cght.getSbr());
            cgd.setYrk(true);
            cgd.setLj(cght.getLj());
            cgd.setEndFlag(true);
            cgd.setCgdmxList(cgdmxList);
            cgd.setKhList(khList);
            cgdDao.save(cgd);

            //采购入库量够了 就自动变成状态  yly
//            Map mapItem = cghtDao.findSumWlyFromCght(cght.getId());
//            Double wly = ((BigDecimal) mapItem.get("WLY")).doubleValue();
//            Map mapItem2 = cghtDao.findSumHtslFromCght(cght.getId());
//            Double htsl = ((BigDecimal) mapItem2.get("HTSL")).doubleValue();
//            if (wly >= htsl) {
//                cght.setZt("yly");
//            }
            cght.setCkZt(1);
            cghtDao.save(cght);
        }
    }
}
